package com.school_admin.service.impl;

import com.school_admin.config.Result;
import com.school_admin.entity.Category;
import com.school_admin.entity.Collection;
import com.school_admin.mapper.CategoryMapper;
import com.school_admin.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2024-03-20
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    private final CategoryMapper categoryMapper;

    @Autowired
    public CategoryServiceImpl(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    // 遍历二级分类
    @Override
    public Result<?> getCategoryList(int type) {
        List<Map> list;
        System.out.println("type = " + type);
        if (type == 1) {
            list = categoryMapper.getCategoryList();
        }else {
            list = categoryMapper.getCategoryList2();
            System.out.println("list = " + list);
        }
        List<Map> resultMap = new ArrayList<>();
        for (Map map : list) {
            if (map.get("parentId") == null || map.get("parentId").equals("")) {
                map.put("children",new ArrayList<>());
                resultMap.add(map);
            }
        }

        for (Map map : list) {
            for (Map resultMap1 : resultMap) {
              if (map.get("parentId") != null &&
                      map.get("parentId").equals(resultMap1.get("categoryId"))
                     ){
                  List<Map> list1 = (ArrayList<Map>) resultMap1.get("children");
                  list1.add(map);
                  break;
              }
            }
        }
        return Result.success(resultMap);
    }

    @Override
    public Result<?> findCategory(Integer categoryId, Integer page, Integer pageSize) {
        int start = (page - 1)  * pageSize;
        List<Map> list = categoryMapper.findCategory(categoryId,start,pageSize);
        if (list.size() == 0) {
            return Result.fail(404, "没有找到对应的数据");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("total",categoryMapper.findCategoryCount(categoryId));
        return Result.success(map);
    }
    void setNum(Category category) {
        this.updateById(category);
    }

    @Override
    public Result<?> getSearchCategoryList(String categoryName) {
        List<Category> list = categoryMapper.getSearchCategoryList(categoryName);
        if (list.size() == 0) {
            return Result.fail(404, "没有找到对应的数据");
        }
        return Result.success(list);
    }
}
